/* 
 * Copyright (c) 2016, Jiehun.com.cn Inc. All Rights Reserved 
 */
package com.kepler.social.web.interceptor;

import com.kepler.social.generic.SecurityHelper;
import com.kepler.social.service.vo.LoginUser;
import com.kepler.social.web.comp.TokenService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;
import java.util.UUID;

import static com.kepler.social.common.constants.SystemConst.TRACE_ID;

@Component
@Slf4j
public class WebInterceptorHandler implements HandlerInterceptor {

    @Resource
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        try{
            MDC.put(TRACE_ID, UUID.randomUUID().toString().replaceAll("-", ""));
            LoginUser loginUser = tokenService.getLoginUser(request);
            if(Objects.nonNull(loginUser)){
                SecurityHelper.setLoginUser(loginUser);
            }

        } catch (Exception e){
            log.error(e.getMessage());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        try{
            MDC.remove(TRACE_ID);
            SecurityHelper.clearLoginUser();
        } catch (Exception e){
            log.error(e.getMessage());
        }
    }
}
